import { get } from 'lodash';

export default async function errorHandle(err, req, res, next) {
  console.error(err);
  if (req.transaction) {
    try {
      await req.transaction.rollback();
    }
    catch (e) {
      console.log('事务回滚失败', e);
      // return next(e);
    }
  }

  if (res.headersSent) { // 响应头已发送
    return next(err);
  }

  const e = {
    errCode: err.code || 1,
    errMsg: 'Server Internal Error'
  };

  if (err.name === 'VersionError') {
    e.errMsg = '数据已过期, 请刷新后重试';
  }
  else if (err.name === 'ExpressValidationError') { // express - validator
    const errors = err.errors.map((error) => `path: ${error.location}/${error.path}, value: ${error.value}, message: ${error.msg}`);
    e.errMsg = errors.join(';');
  }
  else if (/^Sequelize.*Error$/.test(err.name)) { // Sequelize 错误
    e.errCode = `MySQL-${get(err, 'original.errno', 1)}`;
    e.errMsg = get(err, 'original.message', err.message);
    res.original = err.original;
  }
  else { // 通用错误
    e.errMsg = get(err, 'message', e.errMsg);
  }

  return res.send(e);
}
